<template>
    <div class="login__container">
        <video src="../../resource/video/bg_video.d2d602a9.mp4" autoplay loop muted></video>
        <img src="../../resource/img/bg2.fc58c850.png" alt="">
        <h1>千锋管理系统</h1>
        <el-form :model="loginForm" status-icon :rules="rules" ref="loginForm" label-width="100px" class="login__form">
  <el-form-item label="用户名" prop="username">
    <el-input type="text" v-model="loginForm.username" autocomplete="off"></el-input>
  </el-form-item>
  <el-form-item label="密码" prop="password">
    <el-input type="password" v-model="loginForm.password" autocomplete="off"></el-input>
  </el-form-item>
 
  <!-- 验证码 -->
        <el-form-item label="验证码"
                      prop="captcha">
          <el-input type="text"
                    class="captcha ipt"
                    v-model="loginForm.captcha"
                    autocomplete="off"
                    @keydown.native.enter="submitForm('loginForm')">
                    </el-input>
          <span class="captcha-svg"
               v-html="captchaSvg"
               @click="refreshCaptcha"
               >12321312</span>
        </el-form-item>

  <el-form-item>
    <el-button  type="primary" @click="submitForm('loginForm')">登录</el-button>
  </el-form-item>
</el-form>
    </div>
</template>
<script>

import allRoutes from "../../router/allRoutes"
import recursionRoutes from "../../utils/recursionRoutes"
import {getCaptcha,verifyCaptcha,login,getMenuList} from "../../api"
//登录逻辑的实现
//1.收集用户输入的username&password传递给后端
//2.登入通过后，将后端返回的token存到本地，跳转到主页
//3.每次请求的时候，携带token到请求头authorization
//4.展示token校验正确的数据
//5.校验不通过，跳转到登入页
  export default {
    data() {
        //校验用户名
      var validateUsername = (rule, value, callback) => {
         // 4到16位（字母，数字，下滑线，减号）
          //console.log(rule)
        var regExp=/^[a-zA-Z]{1}([a-zA-Z0-9]|[._-]){2,15}$/
        
        if(regExp.test(value)){
            callback()
        }else{
            callback('请输入3到16位（字母，数字，下滑线，减号），只能以字母开头')
        }
      };
   //校验密码
      var validatePassword = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        }  else {
          callback();
        }
      };

//校验验证码
      var validateCaptcha = (rule, value, callback) => {
        if (value === '' || value.length !== 5) {
          callback(new Error('请输入验证码'))
        } else {
          callback()
        }
      }

      return {
          captchaSvg:"",//从服务器获取下来的验证svg结构
        loginForm: {
          username:"",
          password:"",
             captcha: ''
        },
        rules: {
         username: [
            { validator: validateUsername, trigger: 'blur' }
          ],
          password: [
            { validator: validatePassword, trigger: 'blur' }
          ]
        }
      };
    },
    mounted () {
        //获取验证吗
this.getCaptchaCode()
    },
    methods: {
        refreshCaptcha(){
this.getCaptchaCode()
        },
        //获取验证码
        getCaptchaCode(){
        //调用http方法
        getCaptcha().then(res=>{
           // console.log(res)
            this.captchaSvg=res.data.img
            // console.log(this.captchaSvg)
        })
        },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {  //本地表单校验通过
          const loading = this.$loading({
          lock: true,
          text: '正在登录...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
          //发请求
        //先验证验证码是否 正确如果正确再发送登入
        verifyCaptcha(this.loginForm.captcha)
        .then(res=>{
         //console.log(res)
            if(res.data.state){
                //打开加载动画

              
          
                //正确=》校验用户名密码
                let{username,password}=this.loginForm
                login(username,password)
                .then(res=>{
                    
                   if(res.data.state){
                     console.log(res.data.permission);
                       this.$store.commit("SET_USERINFO",res.data.userInfo)
                          this.$store.commit("SET_PERMISSIONBUTTONS",res.data.permission.buttons)
                       //用户名密码正确
                       let{permission,token,userInfo}=res.data
                       //将token储存到本地
                       localStorage.setItem("qf-token",token)
                       localStorage.setItem("qf-userInfo",JSON.stringify(res.data.userInfo))
                       localStorage.setItem("qf-permission-buttons",JSON.stringify(res.data.permission.buttons))
                  //获取用于的权限菜单
                  //因为是async可以.then
                  this.$store.dispatch('FETCH_MENULIST')
                  .then(()=>{
                  //  console.log(621);
                  })
                  //调试
                  // getMenuList()
                  // .then(res=>{
                  //   console.log(res);
                  //   console.log(res.data);
                  //   recursionRoutes(res.data.menuList,allRoutes)
                  // })

                       //跳转到首页
                       this.$router.push("/")
                       loading.close()
                   }else{
                       //用户名密码错误
                       this.getCaptchaCode()  //刷新验证码
                  this.$message.error('用户名密码错误');

                   }
                })
             }else{
                 //错误=》返回错误信息
                  this.$message.error('验证码错误');
                  loading.close()
             }


        })



            // alert('submit!');
          } else {  //本地校验不通过
           // console.log('error submit!!');
            return false;
          }
        });
      }
    }
  }
</script>
<style scoped lang="scss">
/* //加上scoped就不行了
// .login__container{
//     .el-input__inner{
//         width:200px
//     }
// } */

 .captcha {
    width: 100px !important;
    vertical-align: top;
  }
  .captcha-svg {
    background: #fff;
    display: inline-block;
    height: 45px;
    width: 160px;
    text-align: center;
    cursor: pointer;
    border: 0;
    z-index:1;
  }
html,body{
    width: 100%;
  
}
body{
      position: absolute;
    
}
#app{
      background-image: url(../../resource/img/bg2.fc58c850.png);
}
video{
    position: fixed;
    top:0;
    left:0;
    width: 100%;
    height: 100%;
    z-index: -10;
    object-fit: cover;
}
h1{
   color: white;
   text-align: center;
  padding-top: 92px;
  padding-bottom: 22px;
}
.login__container {
 ::v-deep .el-input__inner{
    width:75% ;
}
}
.login__container{
    width: 450px;
    height: 540px;
    position: relative;
    top: 30px;
right: -50%;
// display: flex;
// flex-direction: column;
// justify-content: center;
    background:rgba(2, 50, 139, 0.4);
    border-radius: 8px;
}
.login__container {
::v-deep .el-button{
   width: 260px  !important;
   
}
.login__container {
::v-deep .el-input__inner{
   width:0px;
   
}}


}
.login__container {
  ::v-deep  .el-form-item__label{
color:white
}
}
#app img{
    position: absolute;
    left: 0;
    width: 50%;
    height: 40%;
    left: -70%;
    bottom: 20%;
    opacity: .6;
}



</style>